Post form data to Server using Axios in Vue Js: Axios is a great library to use when making HTTP requests, such as posting form data to an API. By adding the @submit.prevent event handler to the form, you can prevent the default action (form submission) and handle the form data in JavaScript. This event can be used to capture the form data before it is sent to the server. and then use Axios to post the data to the server, ensuring that the data is securely and efficiently transmitted from client to server. In this tutorial, we will learn how to send data from the client side to the server side using axios in Vue.
How to submit form data to an API using Axios in VueJS
Axios is a promise-based HTTP client that can be used to submit form data to an API from within a VueJS application.We will use the axios library to send an asynchronous HTTP request to the server, passing it the form data that we captured in our event handler
Vue Js Get form data on submit
<div id="app">
<form @submit.prevent="submitComment">
<input type="text" v-model="formInfo.name" placeholder="Enter your name"><br><br>
<input type="email" v-model="formInfo.email" placeholder="Enter your email"><br><br>
<input type="number" v-model="formInfo.number" placeholder="Enter your number"><br><br>
<textarea type="text" v-model="formInfo.comment" placeholder="Enter your comment"></textarea><br><br>
<button type="submit">Submit Form</button>
</form>
</div>
<script type="module">
const app = Vue.createApp({
data() {
return {
formInfo: {
name: '',
email: '',
number: '',
comment: ''
}
}
},
methods: {
submitComment() {
axios.post('/comment', this.formInfo)
.then(response => {
console.log(response);
})
.catch(error => {
console.log(error);
});
}
}
})
app.mount("#app")
</script>